const express = require('express');

const app = express();

const session = require('express-session');

app.use(
    session({
        secret: 'itheima',
        resave: false,
        saveUninitialized: true
    })
)

// 托管静态页面
app.use(express.static('./pages'))
    // 解析 POST 提交过来的表单数据
app.use(express.urlencoded({ extended: false }))

app.post('/api/login', (req, res) => {
    if (req.body.username !== 'admin' || req.body.password !== 'admin') {
        return res.send({
            status: 1,
            message: '登陆失败，用户名或密码错误'
        })
    }

    req.session.user = req.body;
    req.session.islogin = true;

    res.send({
        status: 0,
        message: '登录成功'
    })

})

app.get('/api/username', (req, res) => {
    //判断用户是否登录
    if (!req.session.islogin) {
        return res.send({ status: 1, msg: 'fail' })
    }
    res.send({
        status: 0,
        msg: 'success',
        username: req.session.user.username
    })
})

app.post('/api/logout', (req, res) => {
    //清空当前客户端对应的session信息
    req.session.destroy()
    res.send({
        status: 0,
        msg: '退出登录成功'
    })
})

app.listen('80', () => {
    console.log('http://127.0.0.1:80');
})